﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MentorMap.Web;

namespace WebApplication1.UserControls
{
    public partial class EditableLabel : MentorMapUserControl
    {
        public event TextUpdated TextUpdated;

        public string Prefix
        {
            get { return prefix.Text; }
            set { prefix.Text = value; }
        }

        public TextBoxMode TextMode
        {
            get { return txtContent.TextMode; }
            set { txtContent.TextMode = value; }
        }

        public string Text
        {
            get { return lblContent.Text; }
            set
            {
                lblContent.Text = txtContent.Text = value;
            }
        }

        public bool IsRequired { get; set; }

        public EditableLabel()
        {
            IsRequired = false;
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            reqContent.ValidationGroup = btnUpdate.ValidationGroup = "content" + this.ClientID;
            btnUpdate.Click += new EventHandler(btnUpdate_Click);

            Page.ClientScript.RegisterClientScriptInclude(GetType(), "EditableLabel", "/Scripts/EditableLabel.js");
        }

        void btnUpdate_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                lblContent.Text = txtContent.Text;
                pnlEditVersion.Style[HtmlTextWriterStyle.Display] = "none";
                if (TextUpdated != null)
                    TextUpdated(txtContent.Text);
            }
            else
            {
                lblContent.Style[HtmlTextWriterStyle.Display] = "none";
                pnlEditVersion.Style[HtmlTextWriterStyle.Display] = "block";
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            bool _allowEdit = false;
            if (Page is MentorMapEditablePage)
                _allowEdit = ((MentorMapEditablePage)Page).AllowEdits;

            reqContent.Visible = IsRequired;
            pnlEditVersion.Visible = _allowEdit;
            string js = String.Format("editLabelToggle('{0}');", this.ClientID);
            lblContent.Attributes["onclick"] = _allowEdit ? js : String.Empty;
            btnCancel.Attributes["onclick"] = _allowEdit ? js : String.Empty;
        }
    }
}